package com.deer.wms.ware.task.web;

import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.ware.task.model.Wave.*;
import com.deer.wms.ware.task.service.WaveDetailService;
import com.deer.wms.ware.task.service.WaveMasterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;

import java.util.List;

/**
* Created by ll on 2020/02/02.
*/
@RestController
@RequestMapping("/wave/details")
public class WaveDetailController {

    @Autowired
    private WaveDetailService waveDetailService;
    @Autowired
    private WaveMasterService waveMasterService;

    @PostMapping
    public Result add(@RequestBody WaveDetail waveDetail) {
        waveDetailService.save(waveDetail);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/addFromSo")
    public Result addFromSo(@RequestBody WaveDetailInsertData insertData) {
        WaveMaster wave = waveMasterService.getById(insertData.getWaveMasterId());
        for (Integer soId : insertData.getSoMasterIds()) {
            List<WaveDetailDto> waveDetail1 = waveDetailService.findList(new WaveDetailCriteria(soId));
            if(waveDetail1.size()>0){
                return ResultGenerator.genFailResult(CommonCode.SERVER_INERNAL_ERROR,"选中工单中有已添加批次",null);
            }
            WaveDetail waveDetail = new WaveDetail();
            waveDetail.setWaveMasterId(wave.getWaveId());
            waveDetail.setSoMasterId(soId);
            waveDetailService.save(waveDetail);
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        waveDetailService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    public Result update(@RequestBody WaveDetail waveDetail) {
        waveDetailService.updateById(waveDetail);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        WaveDetail waveDetail = waveDetailService.getById(id);
        return ResultGenerator.genSuccessResult(waveDetail);
    }

    @GetMapping
    public Result list(WaveDetailCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<WaveDetailDto> list = waveDetailService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }
}
